import wepy from 'wepy'

export default class httpMixin extends wepy.mixin {
  /* =================== [$get 发起GET请求] =================== */
  $get(
    {url = '', headers = {}, data = {} },
    {success = () => {}, fail = () => {}, complete = () => {} }
  ) {
    const methods = 'GET'
    this.$ajax(
      {url, headers, methods, data},
      {success, fail, complete }
    )
  }

  /* =================== [$post 发起POST请求] =================== */
  $post(
    {url = '', headers = {}, data = {} },
    {success = () => {}, fail = () => {}, complete = () => {} }
  ) {
    const methods = 'POST'
    this.$ajax(
      {url, headers, methods, data},
      {success, fail, complete }
    )
  }

  /**
   * [ajax 统一请求方法]
   * @param  {[type]}  item [description]
   * @return {Boolean}      [description]
   */

  $ajax(
    {url = '', headers = {}, methods = 'GET', data = {} },
    {success = () => {}, fail = () => {}, complete = () => {} }
  ) {
    // 增强体验：加载中
    wx.showNavigationBarLoading()
    let sessionId = wx.getStorageSync('sessionId') || null;
    let account = wx.getStorageSync('account') || null;

    // 构造请求体
    const request = {
      url,
      method: ['GET', 'POST'].indexOf(methods) > -1 ? methods : 'GET',
      header: Object.assign({
        sessionid: sessionId,
        account: account,
        'content-type': 'application/x-www-form-urlencoded'
        // set something global
      }, headers),
      data: Object.assign({
        // set something global
      }, data)
    }


    // 发起请求
    wepy.request(Object.assign(request, {
      success: ({ statusCode, data }) => {

        // 状态码正常 & 确认有数据
        if (0 === +data.head.returnCode && 0 === +data.head.subCode) {
          // 成功回调
          return setTimeout(() => {
            this.isFunction(success) && success(data)
            this.$apply()
          })
        } else if(0 !== +data.head.returnCode){
          this.$alert('提示', data.head.returnMsg)
        }else if(0 !== +data.head.subCode){
          // 失败回调：其他情况
          return setTimeout(() => {
            if(data.head.subCode===110101){
              wx.removeStorageSync('account')
              wx.removeStorageSync('sessionId')
              wepy.reLaunch({
                url: "/pages/login"
              });
            }else if(data.head.subCode===110106){
              this.isFunction(fail) && fail(data)
              this.$apply()
            }else {
              this.$alert('提示', data.head.subMsg)
              this.isFunction(fail) && fail(data)
              this.$apply()
            }
          })
        }
      },
      fail: ({ statusCode, data }) => {

        // 失败回调
        return setTimeout(() => {
          this.isFunction(fail) && fail(data)
          this.$apply()
        })
      },
      complete: (res) => {
        // 隐藏加载提示
        wx.hideNavigationBarLoading()
        // 停止下拉状态
        wx.stopPullDownRefresh()
        // 完成回调
        return (() => {
          this.isFunction(complete) && complete(res)
          this.$apply()
        })()
      }
    }))
  }
}

